package com.example.hobbyplanetserve.config;

import com.example.hobbyplanetserve.Result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {


    @Value("${spring.security.loginType}")
    private String loginType;

    private static ObjectMapper objectMapper=new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        //如果配置了json格式返回则返回json串
        if(loginType.equals("JSON")){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(Result.ok()));
        }else {
            //否则返回登录之前的页面
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}